﻿using UhakVoca.Data;

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Windows.Storage.Pickers;
using Windows.Storage;
using System.Text;
using System.Diagnostics;
using SQLite;
using Windows.Storage.Streams;

// The Grouped Items Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234231

namespace UhakVoca
{
    /// <summary>
    /// A page that displays a grouped collection of items.
    /// </summary>
    public sealed partial class GroupedItemsPage : UhakVoca.Common.LayoutAwarePage
    {
        //Database이름
        const string VocaDicDB = "VocaDicDB.db";
        public GroupedItemsPage()
        {
            this.InitializeComponent();
        }

        /// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="navigationParameter">The parameter value passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
        /// </param>
        /// <param name="pageState">A dictionary of state preserved by this page during an earlier
        /// session.  This will be null the first time a page is visited.</param>
        protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {
            // TODO: Create an appropriate data model for your problem domain to replace the sample data
            var sampleDataGroups = SampleDataSource.GetGroups((String)navigationParameter);
            this.DefaultViewModel["Groups"] = sampleDataGroups;
        }

        /// <summary>
        /// Invoked when a group header is clicked.
        /// </summary>
        /// <param name="sender">The Button used as a group header for the selected group.</param>
        /// <param name="e">Event data that describes how the click was initiated.</param>
        void Header_Click(object sender, RoutedEventArgs e)
        {
            // Determine what group the Button instance represents
            var group = (sender as FrameworkElement).DataContext;

            // Navigate to the appropriate destination page, configuring the new page
            // by passing required information as a navigation parameter
            this.Frame.Navigate(typeof(GroupDetailPage), ((SampleDataGroup)group).UniqueId);
        }


        /// <summary>
        /// Invoked when an item within a group is clicked.
        /// </summary>
        /// <param name="sender">The GridView (or ListView when the application is snapped)
        /// displaying the item clicked.</param>
        /// <param name="e">Event data that describes the item clicked.</param>
        void ItemView_ItemClick(object sender, ItemClickEventArgs e)
        {
            // Navigate to the appropriate destination page, configuring the new page
            // by passing required information as a navigation parameter
            var itemId = ((SampleDataItem)e.ClickedItem).UniqueId;
            this.Frame.Navigate(typeof(ItemDetailPage), itemId);
        }

        private async void UploadFile_Click(object sender, RoutedEventArgs e)
        {
            FileOpenPicker openPicker = new FileOpenPicker();
            openPicker.ViewMode = PickerViewMode.List;
            openPicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
            openPicker.FileTypeFilter.Add("*");
            StorageFile file = await openPicker.PickSingleFileAsync();
            if (file != null)
            {
                StringBuilder output = new StringBuilder("Picked files:\n");
                output.Append(file.Name + "\n");
                Debug.WriteLine(output.ToString());
                FileParing(file);
                //CreateDatabase();
            }
            else
            {
                Debug.WriteLine ("File is not seleceted or cancelled.");
            }
        }

        private async void Select_Click(object sender, RoutedEventArgs e)
        {
            SQLiteAsyncConnection conn = new SQLiteAsyncConnection(VocaDicDB);
            var query = conn.Table<VocaDic>().OrderByDescending(p => p.Id);
            //리스트 형태로 반환
            var results = await query.ToListAsync();
            //각 데이터 출력
            foreach (var item in results)
            {
                Debug.WriteLine(string.Format("{0}: {1} / {2} / {3} / {4}", item.Id, item.VocaName, item.KoreanExplanation, item.ExampleSentence, item.ExampleSentenceExplanation));
            }
        }


        private async void FileParing(StorageFile file)
        {
            try
            {
                if (file != null)
                {
                    List<VocaDic> vocaItems = new List<VocaDic>();
                    string fileContent = await FileIO.ReadTextAsync(file);
                    var stringReader = new StringReader(fileContent);
                    string line;
                    int countline = 0;
                    while ((line = stringReader.ReadLine()) != null)
                    {
                        if (countline++ == 0)
                            continue;
                        string []items = line.Split('\t');
                        vocaItems.Add(new VocaDic()
                        {
                            VocaName = items[0],
                            PartOfSpeech = items[1],
                            Pronunciation = items[3],
                            KoreanExplanation = items[2],
                            Synonym = items[6],
                            WordFrequency = items[4],
                            ExampleSentence = items[8],
                            ExampleSentenceExplanation = items[9],
                            Category = items[10]
                        });
                        
                    }
                    CreateDatabase(vocaItems);
                    //Debug.WriteLine("The following text was read from '" + file.Name + "':" + Environment.NewLine + Environment.NewLine + fileContent);
                }
            }
            catch (FileNotFoundException)
            {
                //NotifyUserFileNotExist();
            }
        }

        private async void CreateDatabase(List<VocaDic> vocaItems)
        {
            SQLiteAsyncConnection conn = new SQLiteAsyncConnection(VocaDicDB);
            //테이블 생성 - 이미 존재하는 경우에는 다시 생성되지 않음
            var result = await conn.CreateTableAsync<VocaDic>();

            //테이블 레코드 카운트
            var cnt = await conn.Table<VocaDic>().CountAsync();
            int itemcount = vocaItems.Count;
            //초기값 입력
            if (cnt == 0)
            {
                int count = 0;
                while(count < itemcount)
                    await conn.InsertAsync(vocaItems[count++]);
                Debug.WriteLine("db created");
            }

        }
    }
}
